$(function() {
	var str = '<div class="modal" id="modal">';
	str += '<div class="modal-dialog">';
	str += '<div class="modal-content"></div>';
	str += '</div>';
	str += '</div>';
	$("body").append($(str));
	
	var str = '<option value="1">工业领域</option>';
	str += '<option value="2">金融领域</option>';
	str += '<option value="3">电信领域</option>';
	str += '<option value="4">智慧城市</option>';
	//模糊查询中的业务分类
	$('#businessType').append($('<option value="-1">请选择</option>'+str));
	//上传中的业务分类
	$('#upLoadForm [name="businessType"]').append($(str));
	//初始化业务分类
	$('[name="businessType"]').chosen({
		width: "100%",
		search_contains: true,
	});

	//报告版本
	$('[name="state"]').chosen({
		width: "100%",
		search_contains: true,
		
	});
	
	$("#upLoadTemplate").click(function() {
		layer.open({
			type: 1, 
			title : "上传模板",
			area : [ "60%", "80%" ],
			content: $("#upload"),
			btnAlign: 'c',
			btn: ["添加","关闭"],
			yes:function(){
				$('#upLoadFile').fileinput('upload');
			},
			btn2:function(){
				resetFrom();
			},
			success:function(layero, index){
				uploadUrl = ctxPath + "/report/word/upLoadReport";
				$(".fileDiv").html('<input type="file" id="upLoadFile" class="file" name="file" multiple>');
				initialPreview = [];
				initialPreviewConfig = [];
				upLoadReport($("#upLoadFile"),index,"upload");
			},
			cancel: function(){
				resetFrom();
			}
		});
	});
	
	//初始化bootstrap table
	intiTable("#table");
	
	//模糊查询
	$("#search-btn").click(function(){
		refreshTable();
	});
	// --------
});

//刷新表格
function refreshTable(){
	var params = $("#search-form").serializeJson();
	$('#table').bootstrapTable("refresh", {
		query : params
	});	
}

var edit = '<a href="javascript:void(0);" title="编辑" class="edit"><span class="glyphicon glyphicon-pencil"></span></a>';
var del = '<a href="javascript:void(0);" style="margin-left:13px;" title="删除" class="del"><span class="glyphicon glyphicon-trash"></span></a>';
//var share = '<a href="javascript:void(0);" style="margin-left:13px;" title="分享" class="share"><span class="glyphicon glyphicon-share"></span></a>';
var col = [
	{
		field : "key",
		title : "编号",
		align : "center",
		valign : "middle",
		formatter : function(value, row, index) {
			return index+1;
		}
	},
	{
		field : "reportOldName",
		title : "报告名称",
		align : "center",
		valign : "middle",
	},
	{
		field : "businessType",
		title : "类型",
		align : "center",
		valign : "middle",
		formatter : function(value, row, index) {
			if(value==1){
				return "工业领域";
			}
			if(value==2){
				return "金融领域";
			}
			if(value==3){
				return "电信领域";
			}
			if(value==4){
				return "智慧城市";
			}
			return index;

		}
	},
	{
		field : "author",
		title : "编写人",
		align : "center",
		valign : "middle",
	},
	{
		field : "uploadBy",
		title : "上传人",
		align : "center",
		valign : "middle",
	},
	{
		field : "uploadDate",
		title : "上传时间",
		align : "center",
		valign : "middle",
	},
	{
		field : "state",
		title : "状态",
		align : "center",
		valign : "middle",
		formatter : function(value, row, index) {
			if (value == 0) {
				return "已启用";
			}
			return "已禁用";
		}
	},
	{
		field : "version",
		title : "版本",
		align : "center",
		valign : "middle",
	},
	{
		field : "modifyDate",
		title : "修改时间",
		align : "center",
		valign : "middle",
	},{
		field : "reportDescribe",
		title : "报告描述",
		align : "center",
		valign : "middle",
		width:100,
		class:'colStyle',
		formatter:paramsMatter,
	},
	{
		field : "operation",
		title : "操作",
		clickToSelect : false,
		align : "center",
		valign : "middle",
		events : "operateEvents",
		formatter : function(value, row, index) {
			var url = ctxPath+"/report/word/showlayer";
			var share = '<a class="green" href="javascript:void(0);" style="margin-left:13px;" title="分享"' +
			'data-title="<'+row.reportOldName+'>分享" data-mode="page"'+
			'data-url="'+url+'"'+  
			'data-height=320px '+
			'data-data="{wtid:\''+row.wtid+'\','+
			'fileType:\''+"docx"+'\',reportOldName:\''+row.reportOldName+'\'}" '+
			'><span class="glyphicon glyphicon-share"></span></a>';
			return edit+share+del;

		}
	}];

//bootstrap table绑定数据
function intiTable(selector){
	var $table = $(selector);
	$table.bootstrapTable({ // 对应table标签的id
		url : ctxPath + "/report/word/queryReportList",
		cache : false, // 设置为 false 禁用 AJAX 数据缓存， 默认为true
		pagination : true, // 分页
		paginationLoop : true,// 设置为 true 启用分页条无限循环的功能。
		striped : true,//隔行变色
		clickToSelect : true,// 点击选择
		pageNumber : 1,// 如果设置了分页，首页页码
		pageSize : 10,// 如果设置了分页，页面数据条数
		pageList : [ 15, 30, 45 ], // 如果设置了分页，设置可供选择的页面数据条数。设置为All
		// 则显示所有记录。
		paginationPreText : '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
		paginationNextText : '›',// 指定分页条中下一页按钮的图标或文字,这里是>
		method : 'post',
		contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
		sidePagination: "server", //服务端处理分页
		queryParams : function(params) { // 自定义参数
			return params;
		},
		responseHandler : function(result){
			return result.data;
		},
		columns : col,
	});
}

//bootstrap table的操作列按钮事件
window.operateEvents = {
	"click .edit" : function(e, value, row, index) {
		editReport(row);
	},
	"click .del" : function(e, value, row, index) {
		delReport([row],"你确定要删除这个模板吗？");
	},
//	"click .share" : function(e, value, row, index) {
////		$.cuslayer({
////			mode:"page",
////			url:ctxPath+"/report/word/aa",
////			title:'新建数据源',
////			formId:'datasource-add-form',
////			width:'550px',
////			height:"600px",
////			btn:["保存","关闭"],
////			btn2:function(){
////		
////			},
////			btn3:function(index, layero){
////				//关闭按钮
////				layer.closeAll('tips');
////			}
////		});
//	},
}

function checkInput(){
	var from = $("#upLoadForm");
	if (from.find("[name='author']").val() == "") {
		return "编写人为必填项";
	}
	if (from.find("[name='author']").val().length > 10) {
		return "编写人的名字过长，请控制在10个字符内";
	}
	if (from.find("[name='version']").val() == "") {
		return "版本为必填项";
	}
	if (from.find("[name='version']").val().length > 6) {
		return "版本过长";
	}
	if (from.find("[name='reportDescribe']").val().length > 255) {
		return "描述过长，请控制在255个字之内";
	}
}

function ajaxUpdateReport(index){
	var news = checkInput();
	if (news != undefined) {
//		var str = '<button type="button" class="close kv-error-close" aria-label="Close"><span aria-hidden="true">×</span></button>';
		var str = '<ul><li data-thumb-id="thumb-upLoadFile-11154_asdf.docx" data-file-id="11154_asdf.docx">'+news+'</li></ul>';
		$(".file-error-message").html(str);
		$(".file-error-message").css("display","");
		return;
	}
	var obj = {};
	var form = document.getElementById("upLoadForm");
	var formData = new FormData(form);
	$.ajax({
		url:ctxPath+"/report/word/updateReport",
		type:"post",
		processData: false,
		contentType: false,
		data:formData,
		success:function(result){
			if (result.code == 1) {
				layer.msg(result.msg, {
					icon : 1
				});
				refreshTable();
				layer.close(index);
				resetFrom();
				return;
			}
			layer.msg(result.error, {
				icon : 2
			});
		}
	});
}

//修改报告模板信息
function editReport(row){
	$.ajax({
		url:ctxPath+"/report/word/queryReport",
		type:"post",
		data:{
			"wtid" : row.wtid
		},
		success:function(result){
			var ele;
			$("#upLoadForm [name]").each(function(){
				ele = $(this);
				$.each(result.data,function(key,item){
					if(ele.attr("name") == key){
						ele.val(item);
						return false;
					}
				})
			});
			$("[name='wtid']").val(result.data.wtid);
			$("[name='reportOldPath']").val(row.filePath+"/"+row.reportName);
			$('#upLoadForm [name="businessType"]').trigger('chosen:updated');
			$('[name="state"]').trigger('chosen:updated');
			layer.open({
				type: 1, 
				title : "修改模板",
				area : [ "60%", "80%" ],
				content: $("#upload"),
				btnAlign: 'c',
				btn: ["修改","关闭"],
				yes:function(index){
					var filesCount = $('#upLoadFile').fileinput('getFilesCount');
					if(filesCount == 0){//只修改数据不修改文件
						ajaxUpdateReport(index);
					}else{
						$('#upLoadFile').fileinput('upload');						
					}
				},
				btn2:function(){
					resetFrom();
				},
				success:function(layero, index){
					initialPreview = new Array();
					initialPreviewConfig　=　new Array();
					var str = row.filePath+"/"+row.reportName;
					initialPreview.push(str);
					var config = {
						type:row.fileType,//文件类型
//						size:100,//文件大小
						previewAsData:true,
						caption:row.reportOldName,//文件名
						url:ctxPath+"/report/word/delPreview",//回显中的删除按钮要绑定后台路径才生效
//						key:"100",
					}
					initialPreviewConfig.push(config);
					//初始化fileinput
					$(".fileDiv").html('<input type="file" id="upLoadFile" class="file" name="file">');
					uploadUrl = ctxPath+"/report/word/updateReport";
					upLoadReport($("#upLoadFile"),index,"updata");
				},
				cancel: function(){
					resetFrom();
				}
			});
		}
	});
}

//删除报告
function delReport(data,msg){
	//主键
	var wtidArr = new Array();
	//文件地址
	var filePathArr = new Array();
	$.each(data,function(index,item){
		wtidArr.push(item.wtid);
		filePathArr.push(item.filePath+"/"+item.reportName);
	});
	$.cuslayer({
		title : "删除模板",
		mode : "del",
		msg : msg,
		url : ctxPath + "/report/word/deleteReport",
		data : {
			"wtidArr":JSON.stringify(wtidArr),
			"filePathArr":JSON.stringify(filePathArr)
		},
		callback : function(result) {
			refreshTable();
		}
	});
}

function resetFrom(){
	$("#upLoadForm")[0].reset();
}
//初始化上传插件
var initialPreview = [];
var initialPreviewConfig = [];
var uploadUrl; // 上传的地址
var inputFileDleBtn = '<button type="button" class="kv-file-remove btn btn-sm btn-kv btn-default btn-outline-secondary" title="删除文件" data-url="" data-key=""><i class="glyphicon glyphicon-trash"></i></button>';
function upLoadReport(ele,layerIndex,operation) {
	var a = 1020;
	ele.fileinput({
        language: 'zh',//语种
        uploadUrl: uploadUrl,//controller地址
        showUpload:false,//不适用默认的上传按钮
        allowedFileExtensions: reportFileType,//支持上传的文件类型
        uploadAsync: true, //异步上传
        maxFileSize: reportFileMaxSize,//文件大小，单位：kb
        initialPreviewAsData: true, // 默认标记 
        initialPreviewShowDelete:false,
        minFileCount: operation=="upload"?1:0, //每次上传允许的最少文件数
        maxFileCount: 3, //每次上传允许的最大文件数
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",//字符串，当文件数超过设置的最大计数时显示的消息
        initialPreview:initialPreview,
        initialPreviewConfig:initialPreviewConfig,
//        overwriteInitial:false,
        layoutTemplates:{
            actionUpload:'',//去除上传预览缩略图中的上传图片
            actionZoom:'',   //去除上传预览缩略图中的查看详情预览的缩略图标
            actionDownload:'', //去除上传预览缩略图中的下载图标
            actionDelete:operation=="upload"?inputFileDleBtn:"", //去除上传预览的缩略图中的删除图标
        },
        uploadExtraData: function(previewId, index) {   //额外参数的关键点
            var obj = {};
            var data = $("#upLoadForm").serializeJson();
            $.each(data,function(key,item){
            	if(item != ""){
            		obj[key] = item;
            	}
            });
            if (operation == "update") {
            	obj.reportDescribe = $("[name='reportDescribe']").val();
			}
            return obj;
        }
    });

	//上传之前校验
	ele.on('filepreupload', function(event, data, previewId, index, jqXHR) {
		var news = checkInput();
		if (news != undefined) {
			return {
				message : news
			};
		}
	});
	ele.on('fileuploaded', function(event, data, previewId, index) {
		var result = data.response;
		if (result.code == 1) {
			layer.msg(result.msg, {
				icon : 1
			});
			refreshTable();
			layer.close(layerIndex);
			resetFrom();
			return;
		}
		layer.msg(result.msg, {
			icon : 2
		});
	});
	ele.on('fileuploaderror', function(event, data, msg) {
		if (data.filescount == 0 && operation == "updata") {
			var str = '<ul><li data-thumb-id="thumb-upLoadFile-11154_asdf.docx" data-file-id="11154_asdf.docx">'+
				'您的文件中存在无效文件，当您保存时我们将不会对文件进行更新</li></ul>';
			$(".file-error-message").html(str);
		}
	});
	
	ele.on('fileerror', function(event, data, msg) {
	});
	
}

//悬浮显示值
function paramsMatter(value, row, index) {
	if (value == undefined) {
		return;
	}
	var values = value;
	values = values.replace(/\s+/g,'&nbsp;')//替换空格
	values = values.replace(/\},/,'},\n');//换行
	var span=document.createElement('span');
	span.setAttribute('title',values);
	span.innerHTML = value;
	return span.outerHTML;
}






